<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" label-width="70px" label-position="left" :model="queryParams" :inline="true">
      <el-form-item label="创建时间" prop="endTime">
        <div class="r_flex">
          <el-date-picker
            v-model="queryParams.alltime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            @change="changtime"
          />
        </div>
      </el-form-item>

      <!-- <el-form-item label="标识符" prop="tag">
        <el-input
          v-model="queryParams.tag"
          placeholder="请输入标识符"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button v-hasPermi="['system:dept:add']" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 表格数据 -->
    <el-table v-if="refreshTable" v-loading="loading" border :data="deptList" row-key="deptId" :header-cell-style="{background: $store.state.app.theme.tableBack,color: $store.state.app.theme.tableColor}" :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @sort-change="sortChange">
      <el-table-column align="center" prop="time" sortable label="日期" :show-overflow-tooltip="true" />
      <!-- <el-table-column align="center" prop="type" label="产品类型">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type == 1" size="small">门店</el-tag>
          <el-tag v-if="scope.row.type == 2" size="small" type="warning">平台</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="center" prop="customerNum" sortable label="提交人数" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="applysNum" sortable label="提交订单" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="customerSuccessNum" sortable label="进件成功人数" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="applysSuccessNum" sortable label="进件成功订单" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="averageNum" sortable label="人均进件" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="income" sortable label="预计营收" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="arpu" sortable label="进件人数Arpu" width="150px" :show-overflow-tooltip="true" />

      <!-- <el-table-column align="center" prop="type" label="类型">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type == 0" size="small">内部</el-tag>
          <el-tag v-if="scope.row.type == 1" size="small" type="warning">API</el-tag>
        </template>
      </el-table-column> -->
    
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" v-loading="upMoneyLoding" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="上级渠道" prop="parentId">
          <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级渠道" />
        </el-form-item> -->
        <el-form-item label="渠道名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入渠道名称" />
        </el-form-item>
        <el-form-item v-show="title=='修改渠道'" label="派单余额" prop="pdAmount">
          <div class="r_flex">
            <p style="width: 300px;">{{ form.pdAmount }}</p>
            <el-input v-model="upMoney" placeholder="充值金额" style="margin-right: 10px;">
              <template slot="append">
                <div class="r_cpter" style="color: #1890ff" @click="changMoney(true)">充值</div>
              </template>
            </el-input>
            <el-input v-model="reduceMoney" placeholder="扣减金额">
              <template slot="append">
                <div class="r_cpter" style="color: #ff4949" @click="changMoney(false)">扣减</div>
              </template>
            </el-input>
          </div>
          <!-- <el-input disabled v-model="form.pdAmount" placeholder="请输入派单余额" /> -->

        </el-form-item>
        <el-form-item label="告警余额" prop="warnAmount">
          <el-input v-model="form.warnAmount" placeholder="请输入告警余额" />
        </el-form-item>
        <el-form-item label="专属服务码" prop="serviceCode">
          <el-input v-model="form.serviceCode" placeholder="请输入信贷经理专属服务码" />
        </el-form-item>
        <el-form-item label="标识符" prop="tag">
          <el-input v-model="form.tag" placeholder="请输入标识符（不可输入中文）" @input="form.tag=form.tag.replace(/[^\w\.\/]/ig,'')" />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="类型" prop="type" style="width: 100%">
          <el-select v-model="form.type" placeholder="请选择" style="width: 100%">
            <el-option key="内部" value="0" label="内部">内部</el-option>
            <el-option key="api" value="1" label="api">api</el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.type == 1" label="url" prop="url">
          <el-input v-model="form.url" placeholder="请输入api地址" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild, businessDataTotal, deptCheck, plusMoney, minusMoney } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import { checkPermi } from '@/utils/permission' // 权限判断函数
import moment from 'moment'

import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'ChannelSell',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        // pageNum: 1, // 当前页数
        // pageSize: 10, // 分页大小
        alltime: '',
        startTime: '',
        endTime: ''
      },
      // 数据总条数
      totalPage: 0,
      // 修改ids
      ids: '',
      // 表单参数
      form: {
        parentId: '',
        deptName: '',
        pdAmount: '',
        tag: '',
        leader: '',
        type: '',
        url: '',
        zkStatus: '1',
        serviceCode: '',
        warnAmount: null
      },
      upMoney: '',
      upMoneyLoding: false,
      reduceMoney: '',
      reduceMoneyLoding: '',
      // 表单校验
      rules: {
        // parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
        deptName: [{ required: true, message: '渠道名称不能为空', trigger: 'blur' }],
        // pdAmount: [{ required: true, message: '派单余额不能为空', trigger: 'blur' }],
        tag: [{ required: true, message: '标识符不能为空', trigger: 'blur' }],
        leader: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
        serviceCode: [{ required: true, message: '信贷经理专属服务码不能为空', trigger: 'blur' }],
        url: [{ required: true, message: 'api地址不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    // 初始化时间
    // var moment = require('moment');
    let time01 = moment().subtract(10, 'day').format('YYYY-MM-DD')
    let time02 = moment().endOf('day').format('YYYY-MM-DD')

    this.$set(this.queryParams, "alltime", [
      time01,
      time02,
    ]);
    this.$set(
      this.queryParams,
      "startTime",
      time01
    );
    this.$set(this.queryParams, "endTime", time02);
    this.getList()
  },
  methods: {
    checkPermi,
    // 时间选择
    changtime(newtime) {
      this.queryParams.startTime = newtime ? newtime[0] : ''
      this.queryParams.endTime = newtime ? newtime[1] : ''
    },
    // 金额充值/扣减
    async changMoney(type) {
      this.upMoneyLoding = true
      if (type) {
        await plusMoney({ deptId: this.form.deptId, money: Number(this.upMoney) }).then(res => {
          this.$message.success('充值成功')
          this.upMoney = ''
          this.upMoneyLoding = false
        }).catch(err => {
          this.upMoneyLoding = false
          // this.$message.error("充值失败");
        })
      } else {
        await minusMoney({ deptId: this.form.deptId, money: Number(this.reduceMoney) }).then(res => {
          this.$message.success('扣减成功')
          this.reduceMoney = ''
          this.upMoneyLoding = false
        }).catch(err => {
          // this.$message.error("扣减失败");
          this.upMoneyLoding = false
        })
      }
      // 更新余额
      getDept(this.form.deptId).then(response => {
        this.form.pdAmount = response.data.pdAmount
        this.getList()
      })
    },
    // 跳转数据统计
    jumpRouter(data) {
      this.$router.push({ path: '/dataControl/dataLargeConsumption', query: { name: data.deptName }})
    },
    // 排序类别 descending
    sortChange(data, value) {
      this.queryParams.isAsc = data.order === 'descending' ? 'asc' : 'desc'
      this.queryParams.orderByColumn = data.prop
      this.getList()
    },
    // 分页请求
    handlePageChange(data) {
      this.queryParams.pageNum = data
      this.getList()
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true
      businessDataTotal(this.queryParams).then(response => {
        // const newparm = []
        // response.rows.map(val => { if (val.parentId !== 0) { newparm.push(val) } })
        this.deptList = response.data
        // this.totalPage = response.total
        this.loading = false
      }).finally(() => { this.loading = false })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        parentId: '',
        deptName: '',
        pdAmount: '',
        tag: '',
        leader: '',
        type: '',
        url: '',
        zkStatus: '1'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (row !== undefined) {
        this.form.parentId = row.deptId
      }
      this.open = true
      this.title = '添加渠道'
      listDept().then(response => {
        // 默认上级渠道是若依
        // 遍历默认取第一个父级渠道
        const newparm = response.data.filter(val => val.parentId === 0)[0].deptId
        // console.log(newparm, 'newparm')
        this.form.parentId = newparm
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true
      this.reset()
      this.ids = row.deptId
      const deptId = row.deptId || this.ids
      getDept(deptId).then(response => {
        this.loading = false
        this.form = response.data
        this.form.type = String(response.data.type)

        // this.form.deptId = response.data.deptId
        // this.form.parentId = response.data.parentId
        // this.form.deptName = response.data.deptName
        // this.form.warnAmount = Number(response.data.warnAmount)
        // this.form.pdAmount = response.data.pdAmount
        // this.form.tag = response.data.tag
        // this.form.leader = response.data.leader
        // this.form.type = String(response.data.type)
        // this.form.url = response.data.url
        // this.form.zkStatus = String(response.data.zkStatus)
        this.open = true
        this.title = '修改渠道'
      }).finally(() => { this.loading = false })
      listDeptExcludeChild(row.deptId).then(response => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    // 修改自动派单状态
    statusUp(tag, row) {
      const param = {
        deptId: row.deptId,
        parentId: row.parentId
      }
      if (tag === 'zdpdStatus') {
        param.zdpdStatus = row.zdpdStatus
      }
      if (tag === 'smsStatus') {
        param.smsStatus = row.smsStatus
      }
      if (tag === 'zkStatus') {
        param.zkStatus = row.zkStatus
      }
      // if(tag == 'status'){
      //   param.status = row.status
      // }
      deptCheck(param).then(response => {
        if (response.code != '200') {
          this.$modal.msgError(response.msg)
          this.getList()
        } else {
          this.$modal.msgSuccess('修改成功')
          this.getList()
        }
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.deptId !== undefined) {
            updateDept(this.form).then(response => {
              if (response.code !== 200) {
                this.$modal.msgError(response.msg)
              } else {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addDept(this.form).then(response => {
              if (response.code !== 200) {
                this.$modal.msgError(response.msg)
              } else {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.deptName + '"的数据项？')
        .then(function() {
          return delDept(row.deptId)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    renderHeader(h, { column, $index }) {
      // console.log(column)
      return [
        column.label,
        h(
          'el-tooltip',
          {
            props: {
              content: (function() {
                // return '效率值 = (周期内完成工单难度系数之和)/周期'
                // const label = column.label
                switch (column.property) {
                  case 'status':
                    return '关闭渠道状态会同步关闭渠道下管理员账号状态'
                }
              })(),
              placement: 'top'
            }
          },
          [
            h('span', {
              class: {
                'el-icon-question': true
              }
            })
          ]
        )
      ]
    }
  }
}
</script>
